<template>
  <div class="pagination">
    <span class="page-btn page-pre" @click="onPagePre"><i class="iconfont icon-shangyiye"></i></span>
    <template v-for="item in pageArray">
      <span class="text" v-if="item == '...'">{{item}}</span>
      <span class="page-btn" v-if="item != '...'" :class="{active: item==index}" @click="onPageClick(item)">{{item}}</span>
    </template>
    <span class="page-btn page-next" @click="onPageNext"><i class="iconfont icon-xiayiye"></i></span>
  </div>
</template>
<script>
export default {
  data() {
    return {}
  },
  props: {
    index: Number,
    total: Number
  },
  methods: {
    onPageClick(n) {
      if (n === this.index) {
        return
      }
      this.emitPageChange(n)
    },
    onPagePre() {
      var n = this.index - 1
      if (n < 1) {
        this.$toasted.show('已经是第一页了')
        return
      }
      this.emitPageChange(n)
    },
    onPageNext() {
      var n = this.index + 1
      if (n > this.total) {
        this.$toasted.show('已经是最后一页了')
        return
      }
      this.emitPageChange(n)
    },
    emitPageChange(n) {
      this.$emit('pagechange', n)
    }
  },
  computed: {
    pageArray() {
      if (this.total <= 10) {
        return Array.from(new Array(this.total), (val, index) => index + 1)
      }
      if (this.index < 5) {
        return [1, 2, 3, 4, 5, '...', this.total]
      } else if (this.index > this.total - 4) {
        return [1, '...', this.total - 4, this.total - 3, this.total - 2, this.total - 1, this.total]
      } else {
        return [1, '...', this.index - 2, this.index - 1, this.index, this.index + 1, this.index + 2, '...', this.total]
      }
    }
  }
}

</script>
<style scoped>
.pagination {
  width: auto;
  margin: 40px auto 0;
  text-align: center;
  font-size: 0;
}

.text {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 22px;
  padding: 4px 0;
  margin: 0 2px;
  font-size: 14px;
}

.page-btn {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  width: 30px;
  font-size: 14px;
  border: 1px solid #dddddd;
  box-sizing: border-box;
  cursor: pointer;
  color: #282828;
  background-color: #fff;
}

.page-btn.active,
.page-btn:hover {
  border-color: #01378c;
  background-color: #01378c;
  color: #fff;
}

.page-pre,
.page-next {
  color: #7f7f7f;
  font-size: 12px;
  vertical-align: top;
}

</style>
